package club.calong.sanniu.service;

import club.calong.sanniu.http.response.ListResponseData;
import club.calong.sanniu.pojo.Plate;
import club.calong.sanniu.pojo.Video;
import club.calong.sanniu.repository.VideoRepository;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.tomcat.util.http.fileupload.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;

@Service
public class VideoService {

    @Value("${app.host}")
    String APP_HOST;

    @Value("${app.video.path}")
    String VIDEO_PATH;

    VideoRepository repository;

    @Autowired
    public VideoService(VideoRepository repository) {
        this.repository = repository;
    }

    public boolean save (Video video) {

        return repository.insert(video) == 1;
    }

    public Object page(Integer page, Integer size) {

        QueryWrapper<Video> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc(Plate.ID);
        if (page != null && size != null) {
            Page<Video> videoPage = repository.selectPage(new Page<>(page, size), wrapper);
            return new ListResponseData<>(videoPage.getRecords(), videoPage.getTotal());
        } else {
            return repository.selectList(wrapper);
        }
    }

    public boolean delete(Integer id) {

        Video video = repository.selectById(id);
        if (video != null && video.getUrl() != null) {
            File file = new File(video.getUrl()
                    .replace(APP_HOST + "res/video/", VIDEO_PATH));
            return file.exists() && file.delete() && repository.deleteById(id) == 1;
        } else {
            return false;
        }
    }
}
